import { Modal, message } from 'antd';
import { axhttp } from '@/shared/axhttp';
import { axhttp as axhttpx } from '@/utils/axhttp';
import { axurl } from '@/shared/axurl';
import { AxTemplate } from '@/components/AxBase/AxTemplate';
import { router } from 'umi';

export const axhelper = {
  getUserInfo: () => {
    return JSON.parse(localStorage.getItem('login_user') || '{}');
  },
  /** 重写登录 */
  reLogin: () => {
    Modal.confirm({
      title: '超时提示',
      content: '登录超时，请重新登录！',
      onOk() {
        let { hash } = location;
        if (hash) {
          hash = hash.substr(1, hash.length - 1);
          const url = hash.split('?')[0];
          if (url !== '/user/token') localStorage.setItem('ax-auth-router', url);
        }
        axhelper.login();
      },
      onCancel: () => Modal.destroyAll(),
    });
  },

  login: () => {
    const user = JSON.parse(localStorage.getItem('ax-data-user'));
    const app = JSON.parse(localStorage.getItem('ax-data-app'));
    let params = {};
    if (user && app) {
      params = {
        userId: user.userId,
        appId: app.appId,
      };
    }
    localStorage.setItem('ax-auth-token', null);
    // document.location.href = `${axurl.system.login}/?userId=${user ? user.userId : ''}&appId=${app ? app.appId : ''}&returnHost=${encodeURIComponent(
    //   location.host,
    // )}`;
    document.location.href = `${axurl.system.login}/?returnHost=${encodeURIComponent(
      location.origin,
    )}`;

    // axhttp.get(axurl.system.logout, params).finally(() => {
    //   document.location.href = `${axurl.system.login}?returnHost=${encodeURIComponent(
    //     location.host,
    //   )}`;
    // });
  },

  /** 获取用户token */
  getToken: () => {
    const ax_token = localStorage.getItem('ax-auth-token');
    if (!ax_token || ax_token === 'null') {
      return false;
    }
    return true;
  },

  /** 获取字典 */
  getDictionary: () => {
    axhttpx.getXhr('/api/dictionary/readx').then(res => {
      localStorage.setItem('ax-data-dictionary', JSON.stringify(res.data));
    });
  },

  /** 通过枚举值获取字典 */
  getDicByEnumName: enumName => {
    if (enumName && enumName === 'axBooleanType') {
      return [
        {
          text: '是',
          value: 'true',
        },
        {
          text: '否',
          value: 'false',
        },
      ];
    }
    if (enumName) {
      let dic = localStorage.getItem('ax-data-dictionary');
      if (dic && dic !== 'null') {
        dic = JSON.parse(dic);
      }

      if (dic) {
        return dic[enumName] || [];
      }
    }
    return [];
  },

  /** 获取字典文本 */
  getDicText: (enumName, value) => {
    const finder = axhelper.getDicByEnumName(enumName);
    if (finder) {
      const obj = finder.find(i => i.value == value);
      if (obj) {
        return obj.text;
      }
    }
    if (enumName === 'axBooleanType') {
      return value === true || value === 1 ? '是' : '否';
    }
    return null;
  },

  /** 通过值，获取下拉列表文本
   * @param v 值
   * @param d 列数据
   */
  getTextByValue: (v, d) => {
    if (d) {
      const obj = d.find(i => i.value == v);
      if (obj) {
        return obj.text;
      }
    }
    return null;
  },

  /** 通过值，获取下拉树文本
   * @param v 值
   * @param d 树数据
   */
  getTreeTextByValue: (v, d) => {
    let f = null;
    if (v && Array.isArray(d)) {
      d.some(i => {
        if (i.id === v) {
          f = i.text;
          return true;
        }
        if (i.children) {
          f = axhelper.getTreeTextByValue(v, i.children);
          return f ? true : false;
        }
      });
    }
    return f;
  },

  /** 将原数据转换为Tree控件可识别的数据
   * @param data 数据
   * @param selectable 可选的节点，如设置为leaf，就只能叶子节点可选（默认全部可选）
   * @param handleDisabled 是否可用的处理函数
   */
  transToTreeData: (data, selectable = undefined, handleDisabled = undefined, extraInfo = {}) => {
    const tdata = [];

    if (data && Array.isArray(data)) {
      data.forEach(i => {
        let children = [];
        if (i.children) {
          children = axhelper.transToTreeData(i.children, selectable, handleDisabled, extraInfo);
        }
        let disabled = false;
        if (handleDisabled) disabled = handleDisabled(i);
        tdata.push({
          key: i.id,
          value: i.id,
          extraId: extraInfo.extraId && i[extraInfo.extraId],
          title: i.text,
          selectable:
            selectable === 'leaf'
              ? i.leaf === true || !i.children || i.children.length === 0
                ? true
                : false
              : true,
          disabled: disabled,
          children,
        });
      });
    }

    return tdata;
  },

  /** 获取checked数据 */
  getCheckedData: data => {
    let checked = [];

    if (data && Array.isArray(data)) {
      data.forEach(i => {
        if (i.isSelect === true) {
          checked.push(i.id);
        }
        let childrenChecked = [];
        if (i.children) {
          childrenChecked = axhelper.getCheckedData(i.children);
        }
        checked = checked.concat(childrenChecked);
      });
    }

    return checked;
  },

  /**
   * 将数据转换为标准的[{ value: '1', text: 'Demo' }]格式
   * @param data 需要转换的数据
   * @param valueField 值字段
   * @param displayField 名称字段
   *  */
  transToStandardData: (data, valueField, displayField) => {
    // const tdata = [];

    // if (data && Array.isArray(data)) {
    //   data.forEach(i => {
    //     tdata.push({
    //       value: i[`${valueField}`],
    //       text: i[`${displayField}`],
    //     });
    //   });
    // }

    // return tdata;
    if (data && data.initialData === true) {
      return [];
    } else {
      if (data && Array.isArray(data)) {
        data.forEach(i => {
          i.value = i[`${valueField}`];
          i.text = i[`${displayField}`];
        });
        data.initialData = false;
        data.ax_time_stamp = Date.now().toString();
        return data;
      } else {
        return [];
      }
    }
  },

  /** 获取Url的请求参数 */
  getQueryString: name => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
    const r = window.location.search.substr(1).match(reg);
    let uri = '';
    if (r != null) {
      uri = decodeURI(r[2]);
    }
    const duri = decodeURIComponent(uri);
    if (duri) {
      const api = /\/\/[a-zA-Z]+/.exec(duri);
      if (api && api.length > 0) {
        localStorage.setItem('ax-data-api', api[0].substr(2));
      } else {
        localStorage.removeItem('ax-data-api');
      }
    }
    return duri;
  },

  /** 获取用于存储页面值的key */
  getPageStorageKey: flag => {
    const hash = location.hash;
    if (hash && hash.length > 2) {
      return hash.substr(2, hash.length - 2).replace(/\//g, '-') + '-' + flag;
    }
    return null;
  },

  /** 获取默认机构 */
  getDefaultOrg: (orgs = [], field) => {
    let org;
    const key = axhelper.getPageStorageKey(field);
    if (key) {
      const orgId = localStorage.getItem(key);
      if (orgId) {
        org = orgs.find(f => f.id === orgId);
      }
    }
    if (!org) {
      if (orgs.length > 0) org = orgs[0];
      else org = {};
    }
    return org;
  },

  /** 获取默认方案 */
  getDefaultSelect: (list = [], field) => {
    let item;
    const key = axhelper.getPageStorageKey(field);
    if (key) {
      const selectId = localStorage.getItem(key);
      if (selectId) {
        item = list.find(f => f.id === selectId);
      }
    }
    !item && (item = {});
    return item;
  },

  /** 打印预览 */
  print: html => {
    var iframe = document.getElementById('printFrame');
    if (!iframe) {
      iframe = document.createElement('IFRAME');
      iframe.setAttribute('id', 'printFrame');
      iframe.setAttribute(
        'style',
        'position:absolute;width:0px;height:0px;left:-500px;top:-500px;',
      );
      document.body.appendChild(iframe);
    }

    var iframewindow = iframe.contentWindow;
    var doc = iframewindow.document;
    doc.open();
    doc.write(
      '<script>window.onload=function(){setTimeout(function() { window.print(); }, 50);}</script>',
    );
    doc.write(html);
    doc.close();
  },

  /** 获取hash（router） */
  getHash: () => {
    let { hash } = location;
    hash = hash.substr(1, hash.length - 1);
    const url = hash.split('?')[0];
    return url;
  },

  /** 获取权限 */
  getPermission: () => {
    let { hash } = location;
    if (hash) {
      let permission = 0;
      function getPermission(o, url) {
        if (o) {
          o.some(i => {
            if (permission > 0) {
              return true;
            }
            if (i.url === url) {
              permission = i.permissions;
              return true;
            }
            if (i.children) {
              getPermission(i.children, url);
            }
            return false;
          });
        }
      }
      hash = hash.substr(1, hash.length - 1);
      const url = hash.split('?')[0];
      const menu = JSON.parse(localStorage.getItem('ax-data-menu'));
      getPermission(menu, url);
      if (permission === 0) {
        const router = localStorage.getItem(
          'ax-auth-router-' + localStorage.getItem('ax-data-api'),
        );
        if (router && url.indexOf(router) !== -1) {
          permission = localStorage.getItem('ax-auth-permissions');
        }
      }
      localStorage.setItem('ax-auth-router-' + localStorage.getItem('ax-data-api'), url);
      localStorage.setItem('ax-auth-permissions', permission);
    }
  },

  /** 获取打印模板 */
  getTemplate: (name, obj = {}) => {
    const printTemplate = JSON.parse(localStorage.getItem('ax-data-template'));
    if (printTemplate && printTemplate[name]) {
      const printTable = AxTemplate.render(printTemplate[name], obj);
      return printTable;
    } else {
      message.error('暂无打印模板！');
      return null;
    }
  },

  /** 将金额转换成大写 */
  convertCurrency: function(currencyDigits) {
    // Constants:
    var MAXIMUM_NUMBER = 99999999999.99;
    // Predefine the radix characters and currency symbols for output:
    var CN_ZERO = '零';
    var CN_ONE = '壹';
    var CN_TWO = '贰';
    var CN_THREE = '叁';
    var CN_FOUR = '肆';
    var CN_FIVE = '伍';
    var CN_SIX = '陆';
    var CN_SEVEN = '柒';
    var CN_EIGHT = '捌';
    var CN_NINE = '玖';
    var CN_TEN = '拾';
    var CN_HUNDRED = '佰';
    var CN_THOUSAND = '仟';
    var CN_TEN_THOUSAND = '万';
    var CN_HUNDRED_MILLION = '亿';
    //var CN_SYMBOL = "人民币";
    var CN_SYMBOL = '';
    var CN_DOLLAR = '元';
    var CN_TEN_CENT = '角';
    var CN_CENT = '分';
    var CN_INTEGER = '整';
    // Variables:
    var integral; // Represent integral part of digit number.
    var decimal; // Represent decimal part of digit number.
    var outputCharacters; // The output result.
    var parts;
    var digits, radices, bigRadices, decimals;
    var zeroCount;
    var i, p, d;
    var quotient, modulus;
    // Validate input string:
    currencyDigits = currencyDigits.toString();
    if (currencyDigits == '') {
      return '还没有输入数字！';
    }
    if (currencyDigits.match(/[^,.\d]/) != null) {
      return '请输入有效数字!';
    }
    if (currencyDigits.match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
      return '请输入有效格式数字！';
    }
    // Normalize the format of input digits:
    currencyDigits = currencyDigits.replace(/,/g, ''); // Remove comma delimiters.
    currencyDigits = currencyDigits.replace(/^0+/, ''); // Trim zeros at the beginning.
    // Assert the number is not greater than the maximum number.
    if (Number(currencyDigits) > MAXIMUM_NUMBER) {
      return '您输入的数字太大了!';
    }
    // Process the coversion from currency digits to characters:
    // Separate integral and decimal parts before processing coversion:
    parts = currencyDigits.split('.');
    if (parts.length > 1) {
      integral = parts[0];
      decimal = parts[1];
      // Cut down redundant decimal digits that are after the second.
      decimal = decimal.substr(0, 2);
      if (decimal == '00') {
        decimal = '';
      }
    } else {
      integral = parts[0];
      decimal = '';
    }
    // Prepare the characters corresponding to the digits:
    digits = new Array(
      CN_ZERO,
      CN_ONE,
      CN_TWO,
      CN_THREE,
      CN_FOUR,
      CN_FIVE,
      CN_SIX,
      CN_SEVEN,
      CN_EIGHT,
      CN_NINE,
    );
    radices = new Array('', CN_TEN, CN_HUNDRED, CN_THOUSAND);
    bigRadices = new Array('', CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
    decimals = new Array(CN_TEN_CENT, CN_CENT);
    // Start processing:
    outputCharacters = '';
    // Process integral part if it is larger than 0:
    if (Number(integral) > 0) {
      zeroCount = 0;
      for (i = 0; i < integral.length; i++) {
        p = integral.length - i - 1;
        d = integral.substr(i, 1);
        quotient = p / 4;
        modulus = p % 4;
        if (d == '0') {
          zeroCount++;
        } else {
          if (zeroCount > 0) {
            outputCharacters += digits[0];
          }
          zeroCount = 0;
          outputCharacters += digits[Number(d)] + radices[modulus];
        }
        if (modulus == 0 && zeroCount < 4) {
          outputCharacters += bigRadices[quotient];
        }
      }
      outputCharacters += CN_DOLLAR;
    }
    // Process decimal part if there is:
    if (decimal != '') {
      for (i = 0; i < decimal.length; i++) {
        d = decimal.substr(i, 1);
        if (d != '0') {
          outputCharacters += digits[Number(d)] + decimals[i];
        }
      }
    }
    // Confirm and return the final output string:
    if (outputCharacters == '') {
      outputCharacters = CN_ZERO + CN_DOLLAR;
    }
    if (decimal == '') {
      outputCharacters += CN_INTEGER;
    }
    outputCharacters = CN_SYMBOL + outputCharacters;
    return outputCharacters;
  },

  S4: () => {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  },

  guid: () => {
    return (
      axhelper.S4() +
      axhelper.S4() +
      '-' +
      axhelper.S4() +
      '-' +
      axhelper.S4() +
      '-' +
      axhelper.S4() +
      '-' +
      axhelper.S4() +
      axhelper.S4() +
      axhelper.S4()
    );
  },

  /** 获取数组值 */
  getArrayValue: function(arr, idx) {
    if (arr && arr[idx]) {
      return arr[idx];
    }
    return '';
  },

  /** 浮点数四舍五入，默认保留两位小数 */
  toFixed: (x, e = 2) => {
    let f = parseFloat(x);
    const exponent = Math.pow(10, e);
    if (isNaN(f)) {
      return NaN;
    }
    f = Math.round(x * exponent) / exponent;
    return f;
  },

  handleClickMenu: (e, url) => {
    const children = e.currentTarget.parentElement.children;
    for (let i = 0; i < children.length; i++) {
      children[i].className = 'item';
    }
    e.currentTarget.className = 'item active';
    router.push(url);
  },
};

export const axdatehelper = {
  format: (dateStr, format) => {
    // 对Date的扩展，将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子：
    // (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18
    Date.prototype.Format = function(fmt) {
      var o = {
        'M+': this.getMonth() + 1, //月份
        'd+': this.getDate(), //日
        'H+': this.getHours(), //小时
        'm+': this.getMinutes(), //分
        's+': this.getSeconds(), //秒
        'q+': Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
          );
      return fmt;
    };

    /** 格式化时间 */
    if (!dateStr || dateStr === '') return '';
    const date = new Date(dateStr);
    return date.Format(format);
  },
  Dateformat: (date, format) => {
    // 对Date的扩展，将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子：
    // (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18
    Date.prototype.Format = function(fmt) {
      var o = {
        'M+': this.getMonth() + 1, //月份
        'd+': this.getDate(), //日
        'H+': this.getHours(), //小时
        'm+': this.getMinutes(), //分
        's+': this.getSeconds(), //秒
        'q+': Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
          );
      return fmt;
    };

    /** 格式化时间 */
    if (!date || date === '') return '';
    return date.Format(format);
  },
};
